package com.example.demo.zhoushengwen.exceptionHandling;

import com.example.demo.Result;
import com.example.demo.Exception.JacksonException;
import com.example.demo.Exception.NotFindException;
import com.example.demo.config.consts.LogConst;
import com.example.demo.config.logconfig.LogBack;
import com.example.demo.zhoushengwen.response.ResponseResult;
import com.example.demo.zhoushengwen.utils.RequestUtil;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;

/**
 * 统一异常捕获类
 **/
@ControllerAdvice //控制器增强
@Slf4j
public class ExceptionCatch
{
    @Autowired
    private HttpServletRequest request;
    
    @Autowired
    private HttpServletResponse response;
    
    //捕获 CustomException异常,及项目中可预知异常
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseResult customException(CustomException e)
    {
        ResponseResult result = new ResponseResult(e.getResultCode());
        LogBack.error("CLIENTIP:{}|UUID:{}|position:{}|level:{}|status:{}|desc:{}|error:{}",
            RequestUtil.getCliectIp(request),
            response.getHeader(LogConst.LOG_UUID),
            LogConst.LOG_EXCEPTIONCATCH,
            LogConst.LOG_STATUS_ERROR,
            LogConst.LOG_END,
            result,
            e);
        response.setHeader(LogConst.HANDLE_RESULT, result.toString());
        return result;
    }
    
    //捕获Exception不可预知异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult exception(Exception exception)
    {
        ResponseResult result = ResponseResult.FAIL(getStatus(request));
        LogBack.error("CLIENTIP:{}|UUID:{}|position:{}|level:{}|status:{}|desc:{}|error:{}",
            RequestUtil.getCliectIp(request),
            response.getHeader(LogConst.LOG_UUID),
            LogConst.LOG_EXCEPTIONCATCH,
            LogConst.LOG_STATUS_ERROR,
            LogConst.LOG_END,
            result,
            exception);
        response.setHeader(LogConst.HANDLE_RESULT, result.toString());
        //错误编号已经拿到了，写一个映射转即可，其他业务逻辑
        return result;
    }
    
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseBody
    public Result<?> handlerNoFoundException(NoHandlerFoundException e)
    {
        log.error(e.getMessage(), e);
        return Result.error(404, "路径不存在，请检查路径是否正确");
    }
    
    @ExceptionHandler(DuplicateKeyException.class)
    @ResponseBody
    public Result<?> handleDuplicateKeyException(DuplicateKeyException e)
    {
        log.error(e.getMessage(), e);
        return Result.error("数据库中已存在该记录");
    }
    
    @ExceptionHandler(NotFindException.class)
    @ResponseBody
    public Result<?> handleException(NotFindException e)
    {
        log.error(e.getMessage(), e);
        return Result.error("操作失败,没有找到SJk，" + e.getMessage());
    }
    
    @ExceptionHandler(JacksonException.class)
    @ResponseBody
    public Result<?> handleException(JacksonException e)
    {
        LogBack.error("CLIENTIP:{}|UUID:{}|position:{}|level:{}|status:{}|desc:{}|error:{}",
            RequestUtil.getCliectIp(request),
            response.getHeader(LogConst.LOG_UUID),
            LogConst.LOG_EXCEPTIONCATCH,
            LogConst.LOG_STATUS_ERROR,
            LogConst.LOG_END,
            e.getMessage(),
            e);
        response.setHeader(LogConst.HANDLE_RESULT, Result.error("JacksonException，" + e.getMessage()).toString());
        return Result.error("JacksonException，" + e.getMessage());
    }
    
    /**
     * @Author 政辉
     * @param e
     * @return
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public Result<?> HttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e)
    {
        StringBuffer sb = new StringBuffer();
        sb.append("不支持");
        sb.append(e.getMethod());
        sb.append("请求方法，");
        sb.append("支持以下");
        String[] methods = e.getSupportedMethods();
        if (methods != null)
        {
            for (String str : methods)
            {
                sb.append(str);
                sb.append("、");
            }
        }
        log.error(sb.toString(), e);
        //return Result.error("没有权限，请联系管理员授权");
        return Result.error(405, sb.toString());
    }
    
    /** 
     * spring默认上传大小100MB 超出大小捕获异常MaxUploadSizeExceededException 
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseBody
    public Result<?> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e)
    {
        log.error(e.getMessage(), e);
        return Result.error("文件大小超出10MB限制, 请压缩或降低文件质量! ");
    }
    
    @ExceptionHandler(DataIntegrityViolationException.class)
    @ResponseBody
    public Result<?> handleDataIntegrityViolationException(DataIntegrityViolationException e)
    {
        log.error(e.getMessage(), e);
        return Result.error("字段太长,超出数据库字段的长度");
    }
    
    /**
     * 获取响应状态码
     * @param request
     * @return
     */
    private HttpStatus getStatus(HttpServletRequest request)
    {
        Integer statusCode = (Integer)request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null)
        {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
}
